import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket=null;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        socket=new Socket(serverIP,serverPort);
        //在创建socket的同时，和服务器建立连接，就要告诉soket服务器在哪里，三次握手
    }
    public void start(){
        //读取服务器返回的响应，把响应显示在控制台
        Scanner scanner=new Scanner(System.in);
        try (InputStream inputStream= socket.getInputStream(); OutputStream outputStream= socket.getOutputStream()){
            PrintWriter printWriter=new PrintWriter(outputStream);
            Scanner scannerwoker=new Scanner(inputStream);
            while (true){
                System.out.print("->");
                String request=scanner.next();//从控制台读取用户输入作为请求
                printWriter.println(request);
                printWriter.flush();//刷新缓存
                //读取服务器的响应
                String response=scannerwoker.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client=new TcpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
